import { message } from 'antd'
const BASE_URL = 'http://42.192.83.237:8080'
export function myFectch({ url = 'http://42.192.83.237:8080', method = 'get', data = {} , headers='application/json'}) {
    const token=sessionStorage.getItem("token") || "";
    if(!url.includes('http')) url = BASE_URL + url;
    return new Promise((reslove, reject) => {
        if (method.toLowerCase() === 'post') {
            fetch(url, {
                method,
                headers: {
                    // "content-type": "application/x-www-form-urlencoded",
                    'Content-Type': headers,
                    token
                },
                body: headers==='application/json'?JSON.stringify(data):headers==="multipart/form-data"?data: dealResult(data)
            }).then(res => {
                // console.log(res);
                return res.ok ? res.json() : Promise.reject({
                    status: res.status,
                    message: res.statusText
                })
            }).then(res => {  
                reslove(res)
            }).catch(err => {
                // console.log(err);
                message.error('数据请求失败：' + JSON.stringify(err))
                reject(err)
            })
        } else {
            fetch(url,{
                headers:{
                    "content-type": headers,
                    token
                }
            }).then(res => {
                // console.log(res);
                return res.ok ? res.json() : Promise.reject({
                    status: res.status,
                    message: res.statusText
                })
            }).then(res => {
                reslove(res)
            }).catch(err => {
                // console.log(err);
                message.error('数据请求失败：' + JSON.stringify(err))
                reject(err)
            })
        }
    })
}
const dealResult = (target)=>{
    let result = '';
    for(const i in target){
        result += `${i}=${target[i]}&`
    }
    return result
}
// 'name=赵六&pwd=000'<==={name:'赵六',pwd=000}